﻿using Company.Database.Entities;

namespace Company.Database.Sqlite
{
    public class UserRepository : RepositoryBase,IUserRepository
    {
        public bool Delete(UserEntity entity)
        {
            db.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
            return db.SaveChanges() > 0;
        }

        public List<UserEntity> GetAll()
        {
            return db.Users.ToList();
        }

        public bool Insert(UserEntity entity)
        {
            db.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Added;
            return db.SaveChanges() > 0;
        }

        public bool Login(string username, string password, out UserEntity user)
        {
            user = null;
            var list = db.Users.Where(t => t.UserName.Equals(username) &&
            t.Password.Equals(password)).ToList();
            if (list != null && list.Count > 0)
            {
                user = list.FirstOrDefault() ?? new();
                return true;
            }
            return false;
        }

        public UserEntity? Search(string username)
        {
            return db.Users.Where(t => t.UserName == username).FirstOrDefault();
        }

        public bool Update(UserEntity entity)
        {
            db.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            return db.SaveChanges() > 0;
        }
    }
}
